package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"stores/cache"
	"stores/models"
	"time"
)

type StoreController struct {
	beego.Controller
}

func (c *StoreController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	var err error

	name := c.GetString("name")
	types := c.GetString("types")
	userName := c.GetString("user_name")
	tel := c.GetString("tel")
	status := c.GetString("status")

	stores := models.Store{
		Name:     name,
		Types:    types,
		UserName: userName,
		Tel:      tel,
		Status:   status,
	}

	if err = stores.GetNameById(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	if err = stores.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "门店添加失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "门店添加成功",
	}
	c.ServeJSON()
} //添加
func (c *StoreController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	var err error

	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")

	key := fmt.Sprintf("list_%d_%d", page, pageSize)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	var store models.Store
	var list []models.Store

	if cacheData == "" {
		list, _ = store.List(page, pageSize)
		if len(list) != 0 {
			jsonData, _ := json.Marshal(list)
			cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour)
		}
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	var count int64
	models.DB.Model(&models.Store{}).Count(&count)

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "门店展示成功",
		"data":    list,
		"count":   count,
	}
	c.ServeJSON()
} //列表
func (c *StoreController) Update() {
	var err error

	id, _ := c.GetInt("id")
	name := c.GetString("name")
	types := c.GetString("types")
	userName := c.GetString("user_name")
	tel := c.GetString("tel")
	status := c.GetString("status")

	var store models.Store
	store.ID = uint(id)
	store.Name = name
	store.Types = types
	store.UserName = userName
	store.Tel = tel
	store.Status = status

	if err = store.GetNameById(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	if store.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "当前店铺不存在",
		}
		c.ServeJSON()
		return
	}

	if err = store.Update(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "修改失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "修改成功",
	}
	c.ServeJSON()
}
